# -*- coding: binary -*-

# GitLab Groups mixin
module Msf::Exploit::Remote::HTTP::Gitlab::Rest::V4::Groups
  # Create a new group
  #
  # @return [String,nil] Group ID if successful create, nil otherwise
  def gitlab_create_group(group_name, api_token)
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/api/v4/groups'),
      'ctype' => 'application/json',
      'headers' => {
        'PRIVATE-TOKEN' => api_token
      },
      'data' => {
        name: group_name, path: group_name, visibility: 'public'
      }.to_json
    })

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError.new message: 'Request timed out' unless res

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::GroupError, "Unable to create group. Unexpected HTTP #{res.code} response." if res.code != 201

    group = JSON.parse(res.body)

    return group if group

    nil
  end

  # Delete a group
  #
  # @return [Boolean,GitLabClientError] True if successful deleted, Msf::Exploit::Remote::HTTP::Gitlab::GitLabClientError otherwise
  def gitlab_delete_group(group_id, api_token)
    res = send_request_cgi({
      'method' => 'DELETE',
      'uri' => normalize_uri('/api/v4/groups', group_id),
      'ctype' => 'application/json',
      'headers' => {
        'PRIVATE-TOKEN' => api_token
      }
    })

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError.new message: 'Request timed out' unless res

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::GroupError, "Unable to delete group. Unexpected HTTP #{res.code} response." if res.code != 202

    true
  end
end
